//
//  NIMDB.swift
//  Demo
//
//  Created by YMac on 2020/1/1.
//  Copyright © 2020 zchd. All rights reserved.
//
import Foundation

open class YDBOperater {
    public class func getDB() -> FMDatabase {
        let db = FMDatabase(url: try! FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent(YConfig.dbName))
        let dbVersion = UserDefaults.standard.integer(forKey: "YFree_save_dbVersion")
        if dbVersion != YConfig.dbVersion {
            YConfig.YDBTableSQL.tableNames?.forEach {
                try? db.executeUpdate("drop table if exists \($0)", values: nil)
            }
            UserDefaults.standard.set(YConfig.dbVersion, forKey: "YFree_save_dbVersion")
        }
        YConfig.YDBTableSQL.createTableSqls?.forEach {
            try? db.executeUpdate($0, values: nil)
        }
        return db
    }
    
    open class func exec(_ sql:String, _ params:Any...) -> Bool {
        let db = getDB()
        db.open()
        let result = db.executeUpdate(sql, withArgumentsIn: params)
        db.close()
        return result
    }
    
    open class func query<T:NSObject>(_ sql:String, _ params:Any...) -> [T] {
        let db = getDB()
        db.open()
        var results = [T]()
        do {
            let rs = try db.executeQuery(sql, values: params)
            while rs.next() {
                var result = [String:String]()
                (0 ..< rs.columnCount).forEach {
                    let columnName = rs.columnName(for: $0)!
                    result[columnName] = rs.string(forColumn: columnName)
                }
                results.append(T.mj_object(withKeyValues: result))
            }
        } catch {
        }
        db.close()
        return results
    }
}
